package com.zxb.base.auth;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zxb.core.common.R;
import com.zxb.core.common.Req;
import com.zxb.core.common.User;
import com.zxb.core.dao.auth.AuthUser;
import com.zxb.core.dao.auth.AuthUserDao;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class IdCardController {

    private final AuthUserDao userDao;

    @PostMapping("/user/idCard/change")
    public R changeIdCard(@RequestBody String idCard) {
        if (StrUtil.isBlank(idCard)) {
            return R.error("请输入身份证号");
        }
        if (!IdcardUtil.isValidCard(idCard)) {
            return R.error("请输入正确的身份证号");
        }
        User u = Req.getCurrUser();
        AuthUser user = userDao.getById(u.getId());
        if (userDao.exists(new LambdaQueryWrapper<AuthUser>()
                .eq(AuthUser::getIdCard, idCard)
                .ne(AuthUser::getId, user.getId()))) {
            return R.error("身份证号已经被其他用户占用");
        }
        user.setIdCard(idCard);
        userDao.updateById(user);
        return R.success();
    }

}
